package cn.wolfcode.trip.app.controller.websocket;

import cn.wolfcode.trip.base.domain.Message;
import cn.wolfcode.trip.base.service.IMessageService;
import cn.wolfcode.trip.base.util.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChatResponse implements Runnable{
    private static IMessageService messageService;
    @Autowired
    public void setMessageService(IMessageService messageService){
        ChatResponse.messageService = messageService;
    }
    private Long userId;
    private Long targetId;
    private Integer type;
    private Thread thread;
    private WebSocket webSocket;
    //线程开启方法
    public void start(Long userId, Long targetId, Integer type, WebSocket webSocket){
        this.userId = userId;
        this.targetId = targetId;
        this.type = type;
        this.webSocket = webSocket;
        thread = new Thread(this);
        thread.start();
    }
    //线程关闭方法
    public void close(){
        thread.stop();
    }
    public void run() {
        while(true){
            System.out.println(messageService);
            if(thread.isInterrupted()){
                System.out.println("退出");
                break;
            }
            List<Message> list = messageService.getMessageDialog(userId,targetId,type);
            if (list.size() > 0) {
                ArrayList<Map<String, Object>> list1 = new ArrayList();
                for (Message message : list) {
                    Map<String, Object> map = new HashMap();
                    map.put("headSrc",message.getUser().getHeadImgUrl());
                    map.put("str",message.getContent().getContent());
                    map.put("time",message.getCreatdate().toLocaleString());
                    list1.add(map);
                }
                Map<String, List> map = new HashMap();
                map.put("list",list1);
                try {
                    webSocket.sendMessage(JSONUtil.toJSONString(map));
                } catch (IOException e) {
                    e.printStackTrace();
                    close();
                }
                messageService.batchMarkread(userId,targetId,type);
            }
            try {
                thread.sleep(5000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
